package com.ruoyi.project.exam.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.IdGen;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.project.exam.domain.QuAnswerModel;
import com.ruoyi.project.exam.domain.QuModel;
import com.ruoyi.project.exam.mapper.QuMapper;
import com.ruoyi.project.exam.service.IQuService;

@Service
public class QuServiceImpl implements IQuService {
	@Autowired
	private QuMapper quMapper;

	@Override
	public List<QuModel> selectQuList(QuModel model) {
		return quMapper.selectQuList(model);
	}

	@Override
	@Transactional
	public void insertQu(QuModel model) {
		String quId = IdGen.uuid();
		model.setId(quId);
		model.setCreateBy(ShiroUtils.getLoginName());
		model.setCreateTime(new Date());
		List<QuAnswerModel> answerList = JSONObject.parseArray(model.getAnswer(), QuAnswerModel.class);
		if (answerList != null && !answerList.isEmpty()) {
			for (int i = 0; i < answerList.size(); i++) {
				answerList.get(i).setId(IdGen.uuid());
				answerList.get(i).setQuId(quId);
				answerList.get(i).setSort(i);
			}
			model.setAnswerList(answerList);
		}
		quMapper.insertQu(model);
	}

	@Override
	public Object selectQuById(String id) {
		return quMapper.selectQuById(id);
	}

	@Override
	@Transactional
	public void updateQu(QuModel model) {
		model.setUpdateBy(ShiroUtils.getLoginName());
		model.setUpdateTime(new Date());
		List<QuAnswerModel> answerList = JSONObject.parseArray(model.getAnswer(), QuAnswerModel.class);
		if (answerList != null && !answerList.isEmpty()) {
			for (int i = 0; i < answerList.size(); i++) {
				answerList.get(i).setId(IdGen.uuid());
				answerList.get(i).setQuId(model.getId());
				answerList.get(i).setSort(i);
			}
			model.setAnswerList(answerList);
		}
		quMapper.updateQu(model);
	}

	@Override
	public int deleteQuByIds(String ids) {
		return quMapper.deleteQuByIds(Convert.toStrArray(ids));
	}

	@Override
	@Transactional
	public void importQu(String repoId, List<QuModel> quList, List<QuAnswerModel> quAnswerList) {
		quMapper.importQu(repoId, quList, quAnswerList);
	}

}
